package cn.edu.ecut.util;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.charset.Charset;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;


public class SQLtoFILE {
	public static void main(String[] args) throws IOException, SQLException {
		List<String> listType=new ArrayList<String>();
		List<String> listColumn=new ArrayList<String>();
		JdbcHelper helper=JdbcHelper.getInstance(DatabaseType.ORACLE );
		String select="SELECT e.empno AS eno , e.ename, d.deptno , d.dname FROM emp e JOIN DEPT d ON e.deptno = d.deptno";
		PreparedStatement s = helper.prepare( select );
		// 因为 select 语句中没有 参数占位符 ，所以可以不设置 参数值
		ResultSet rs = s.executeQuery(); // 不要在 executeQuery 参数中再指定 SQL 语句
		ResultSetMetaData rsmd = rs.getMetaData();
		final int columnCount = rsmd.getColumnCount(); // 获取查询结果中的列数 ( 不一定是表中的列数 )
		System.out.println( "查询结果中包含 " + columnCount + " 列");	
		for( int i = 1 ; i <= columnCount ; i++ ) {
			// 获得第 i 列的 标签名 ( 列名 或 列别名 )
			String label = rsmd.getColumnLabel( i ); // 如果指定果列的别名，就返回列的别名
			label = label.toLowerCase();
			listColumn.add(label);
			String typeName = rsmd.getColumnTypeName( i );
			listType.add(typeName);
			System.out.println( label + " ,  " + typeName  );
		}
		System.out.println(listType);
		
		//文件部分
		String TABLENAME="Emp";
		File file =new File(TABLENAME+".java");
		OutputStream fos=new FileOutputStream(file);
		Charset cs=Charset.forName("UTF-8");
		Writer writer=new OutputStreamWriter(fos,cs);
		BufferedWriter bw=new BufferedWriter(writer);
		
		bw.append("public class "+TABLENAME+"{");
		bw.newLine();
		for(int i=0;i<listType.size();i++) {
			String type=listType.get(i);
			String column=listColumn.get(i);
			bw.append("	"+"private "+type+" "+column+";");
			bw.newLine();
			bw.newLine();
		}
		for(int i=0;i<listType.size();i++) {
			String type=listType.get(i);
			String column=listColumn.get(i);
			//type转换
			if(type.contains("CHAR")) {
				type="String";
			}
			else if(type.startsWith("NUM")) {
				type="double";
			}
			else if(type.contains("DATE")) {
				type="LocalDate";
			}
			String string=column.substring(0, 1).toUpperCase() + column.substring(1);
			bw.append("	"+"public "+type+" get"+string+"{");
			bw.newLine();
			bw.append("		"+"return "+"this."+column+";");
			bw.newLine();
			bw.append("	}");
			bw.newLine();
			bw.newLine();
			bw.append("	"+"public void"+" set"+string+"("+type+" "+column+"){");
			bw.newLine();
			bw.append("		"+"this."+column+"="+column+";");
			bw.newLine();
			bw.append("	}");
			bw.newLine();
			bw.newLine();
		}
		bw.append("}");
		bw.close();
		writer.close();
		fos.close();
		
		
	}
}
